package com.evaluationsystem.system.serivce.impl;

import cn.hutool.core.date.DateUtil;
import com.evaluationsystem.Utils.ModularNameUtils;
import com.evaluationsystem.Utils.UserContextUtils;
import com.evaluationsystem.system.dao.DictionaryDao;
import com.evaluationsystem.system.dao.AppraisalDao;
import com.evaluationsystem.system.entity.Tlogs;
import com.evaluationsystem.system.serivce.AppraisalService;
import com.evaluationsystem.system.serivce.TlogsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppraisalServiceImpl implements AppraisalService {

    @Autowired
    AppraisalDao dao;

    @Autowired
    UserContextUtils userContextUtils;

    @Autowired
    DictionaryDao dictionaryDao;

    @Autowired
    TlogsService logsService;

    @Override
    public Map<String, Object> appraisalSelectDatas() {
        Map<String, Object> res = new HashMap<>();
        res.put("code",200);
        res.put("msg","ok");
        //评定类型（类型：005）
        res.put("vappraisalsflg",dictionaryDao.selByType("005"));
        //考核类别（类型：007）
        res.put("vassessflg",dictionaryDao.selByType("007"));
        return res;
    }

    @Override
    public Map<String, Object> appraisalTableDatas(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        PageHelper.startPage(Integer.parseInt(param.get("page").toString()), Integer.parseInt(param.get("limit").toString()));
        List<Map<String, Object>> appraisals =  dao.examinationTableDatas(param);
        PageInfo<Map<String, Object>> PageInfos = new PageInfo<>(appraisals);
        map.put("code","0");//解析接口状态
        map.put("msg","success");//解析提示文本
        map.put("count",PageInfos.getTotal());//解析数据长度
        map.put("data",PageInfos.getList());//解析数据列表
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Map<String, Object> appraisalAdd(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        /*field={vcontent=2, vassessflg=0, vappraisalsflg=0}*/
        /*scoreinfos[{vstandard=1, iscore=1, vno=1}]*/
        Map<String, Object> field = (Map<String, Object>)param.get("field");
        if(StringUtils.isNotEmpty(dao.selContentByContent(field.get("vcontent")))){
            map.put("code","5001");//解析接口状态
            map.put("msg","评定内容已存在");//解析提示文本
            return map;
        }
        String vappraisalsid =  userContextUtils.getMaxid(dao.selMaxAppraisalsId(), "KH", 6, "0");
        String vinsuserid = userContextUtils.getUserId();
        field.put("vappraisalsid",vappraisalsid);
        field.put("vinsuserid",vinsuserid);
        field.put("vinsdate", DateUtil.now());
        try {
            int a = dao.inserttAppraisals(field);
            List<Map<String, Object>> scoreinfos = (List<Map<String, Object>>)param.get("scoreinfos");
            a = logsService.add(new Tlogs()
                    .setVoperationcontent(vappraisalsid)/*操作内容*/
                    .setVmodularname(ModularNameUtils.AppraisalsAdd)/*操作模块名称*/
                    .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                    .setVoperation(userContextUtils.getUserId())/*操作人*/
                    /*.setVrecordscode("评定组ID:"+vpositionid)*/
            );

            for (Map<String, Object> i :scoreinfos) {
                i.put("vappraisalsid",vappraisalsid);
                i.put("vinsuserid",vinsuserid);
                i.put("vinsdate", DateUtil.now());
                i.put("iscore",Integer.parseInt(i.get("iscore").toString()));
                int b  = dao.inserttScoreinfo(i);
                a = logsService.add(new Tlogs()
                        .setVoperationcontent(i.get("vno").toString())/*操作内容*/
                        .setVmodularname(ModularNameUtils.ScoreinfoAdd)/*操作模块名称*/
                        .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                        .setVoperation(userContextUtils.getUserId())/*操作人*/
                        .setVrecordscode(vappraisalsid)
                );
            }
            map.put("code","200");
            map.put("msg","保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code",5002);
            map.put("msg","数据访问异常，请联系管理员");
        }
        return map;
    }

    @Override
    public Map<String, Object> appraisaUpdata(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        /*{field={vappraisalsid=KH000004, vcontent=werfw, vassessflg=2, vappraisalsflg=0,vupduserid,vupddate}, scoreinfos=[]}*/
        /*scoreinfos=[{vstandard=存储, iscore=1, vno=3, newscoreinfo=new, vdelflg=0, vdelflgname=有效}]*/
        Map<String,Object> field = (Map<String, Object>) param.get("field");
       String vcontent =  dao.upSelContentByContent(field);
        if(StringUtils.isNotEmpty(dao.upSelContentByContent(field))){
            map.put("code","5001");//解析接口状态
            map.put("msg","评定内容已存在");//解析提示文本
            return map;
        }
        try {
            field.put("vupduserid",userContextUtils.getUserId());
            field.put("vupddate",DateUtil.now());
            int a = dao.appraisaUpdata(field);
            a = logsService.add(new Tlogs()
                    .setVoperationcontent(field.get("vappraisalsid").toString())/*操作内容*/
                    .setVmodularname(ModularNameUtils.AppraisalsUpdata)/*操作模块名称*/
                    .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                    .setVoperation(userContextUtils.getUserId())/*操作人*/
                    /*.setVrecordscode(vappraisalsid)*/
            );
            List<Map<String,Object>> scoreinfos = (List<Map<String, Object>>) param.get("scoreinfoArr");
            if(scoreinfos.size()>0){
                for (Map<String,Object> scoreinfo :scoreinfos) {
                    scoreinfo.put("vappraisalsid",field.get("vappraisalsid"));
                    scoreinfo.put("vupduserid",userContextUtils.getUserId());
                    scoreinfo.put("vinsdate",DateUtil.now());
                    scoreinfo.put("iscore",Integer.parseInt(scoreinfo.get("iscore").toString()));
                    int b  = dao.inserttScoreinfo(scoreinfo);
                    a = logsService.add(new Tlogs()
                            .setVoperationcontent(scoreinfo.get("vno").toString())/*操作内容*/
                            .setVmodularname(ModularNameUtils.ScoreinfoUpdata)/*操作模块名称*/
                            .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                            .setVoperation(userContextUtils.getUserId())/*操作人*/
                            .setVrecordscode(field.get("vappraisalsid").toString())
                    );
                }
            }
            map.put("code","200");
            map.put("msg","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code","5002");
            map.put("msg","数据访问异常，请联系管理员");
        }
        return map;
    }

    @Override
    public Map<String, Object> appraisalStartAndForbid(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        map.put("vupduserid",userContextUtils.getUserId());
        map.put("vupddate",DateUtil.now());
        try {
            int a = dao.appraisalStartAndForbidByappraisalsid(param);
            a = logsService.add(new Tlogs()
                .setVoperationcontent(param.get("startAndForbid").toString())/*操作内容*/
                .setVmodularname(ModularNameUtils.AppraisalsStartAndForbid)/*操作模块名称*/
                .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                .setVoperation(userContextUtils.getUserId())/*操作人*/
                .setVrecordscode(param.get("vappraisalsid").toString())
            );
            map.put("code","200");
            map.put("msg","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code",5002);
            map.put("msg","数据访问异常，请联系管理员");
        }
        return map;
    }

    @Override
    public Map<String, Object> scoreinfoTableDatas(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        PageHelper.startPage(Integer.parseInt(param.get("page").toString()), Integer.parseInt(param.get("limit").toString()));
        List<Map<String, Object>> scoreinfos =  dao.scoreinfoTableDatas(param);
        PageInfo<Map<String, Object>> PageInfos = new PageInfo<>(scoreinfos);
        map.put("code","0");//解析接口状态
        map.put("msg","success");//解析提示文本
        map.put("count",PageInfos.getTotal());//解析数据长度
        map.put("data",PageInfos.getList());//解析数据列表
        return map;
    }

    @Override
    public Map<String, Object> appraisalAndScoreinfos(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        Map<String, Object> appraisal = dao.selAppraisalByid(param);
        List<Map<String, Object>> scoreinfo = dao.scoreinfoTableDatas(param);
        map.put("code",200);
        map.put("msg","ok");
        map.put("appraisal",appraisal);
        map.put("scoreinfo",scoreinfo);
        return map;
    }

    @Override
    public Map<String, Object> scoreinfoStartAndForbid(Map<String, Object> param) {
        Map<String,Object> map = new HashMap<>();
        param.put("vupduserid",userContextUtils.getUserId());
        param.put("vupddate",DateUtil.now());
        //{vdelflg=1, vappraisalsid=KH000021, vno=1, startAndForbid=禁用, vupduserid=gdy, vupddate=2020-05-08 17:10:51}
        if (param.get("startAndForbid").equals("禁用")){
            if (dao.selScoreInfosByAppraisalsid(param).size()==1){
                map.put("code","5003");
                map.put("msg","至少保留一条选项");
                return map;
            }
        }
        try {
            int a = dao.scoreinfoStartAndForbidByappraisalsid(param);
            Map<String, Object> scoreinfo  = dao.selScoreinfoByAppraisalsIdAndVno(param);
            a = logsService.add(new Tlogs()
                .setVoperationcontent(param.get("startAndForbid").toString())/*操作内容*/
                .setVmodularname(ModularNameUtils.ScoreinfoStartAndForbid)/*操作模块名称*/
                .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                .setVoperation(userContextUtils.getUserId())/*操作人*/
                .setVrecordscode(param.get("vappraisalsid").toString()+"-"+ param.get("vno").toString())
            );
            map.put("code","200");
            map.put("msg","修改成功");
            map.put("data",scoreinfo);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code",5002);
            map.put("msg","数据访问异常，请联系管理员");
        }
        return map;
    }

    @Override
    public Map<String, Object> standardAndIscoreUpdata(Map<String, Object> param) {
        /*{vappraisalsid:主键ID,vno:序号,vstandard:答案,iscore:分值,vupduserid,vupddate}*/
        Map<String,Object> map = new HashMap<>();
        param.put("vupduserid",userContextUtils.getUserId());
        param.put("vupddate",DateUtil.now());
        param.put("iscore",Integer.parseInt(param.get("iscore").toString()));
        try {
            int a = dao.standardAndIscoreUpdata(param);
            a = logsService.add(new Tlogs()
                .setVoperationcontent("答案:"+param.get("vstandard").toString()+",分值:"+param.get("iscore").toString())/*操作内容*/
                .setVmodularname(ModularNameUtils.ScoreinfoUpdata)/*操作模块名称*/
                .setVpagename(ModularNameUtils.Appraisals)/*操作页面名称*/
                .setVoperation(userContextUtils.getUserId())/*操作人*/
                .setVrecordscode(param.get("vappraisalsid").toString()+"-"+ param.get("vno").toString())
            );
            map.put("code","200");
            map.put("msg","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code",5002);
            map.put("msg","数据访问异常，请联系管理员");
        }
        return map;
    }


}
